package com.imooc.reader.portal.utils.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.reader.portal.dto.SmsResult;
import com.imooc.reader.portal.utils.SmsUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class SmsUtilsImpl implements SmsUtils {
    private String aliyunAccessKey ;
    private String aliyunAccessSecret ;
    private String aliyunSmsTemplateCode ;
    private String aliyunSmsVarName ;
    private String aliyunSmsSign ;

    @Override
    public SmsResult sendVerifyCode(String mobile, String verifyCode) throws ServerException, ClientException, JsonProcessingException {
        DefaultProfile defaultProfile = DefaultProfile.getProfile("default", aliyunAccessKey, aliyunAccessSecret);
        IAcsClient client = new DefaultAcsClient(defaultProfile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", aliyunSmsSign);
        request.putQueryParameter("TemplateCode",aliyunSmsTemplateCode);
        //{code:"...."}
        request.putQueryParameter("TemplateParam","{" + aliyunSmsVarName + ":\"" + verifyCode + "\"}");
        CommonResponse commonResponse = client.getCommonResponse(request);
        String ret = commonResponse.getData();
        ObjectMapper objectMapper = new ObjectMapper();
        SmsResult smsResult = objectMapper.readValue(ret, SmsResult.class);
        log.info("{}",smsResult);

        return smsResult;
    }

    public static void main(String[] args) {
        try {
            new SmsUtilsImpl().sendVerifyCode("13601461256", "8854");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
